<?php

use GatewayWorker\Lib\Db;
use GatewayWorker\Lib\Gateway;


class Events
{
    // 当有客户端连接时，将client_id返回，让mvc框架判断当前uid并执行绑定
    public static function onConnect($client_id)
    {
//        $db1 = Db::instance('db1');
//        $insert_id = $db1->insert('test')->cols(array('name' => "FG_onConnect=" . $client_id))->query();
//
//        Gateway::sendToClient($client_id, json_encode(array(
//            'type' => 'init',
//            'client_id' => $client_id
//        )));

//        Gateway::sendToClient($client_id, "\$GN");
    }

    public static function onMessage($client_id, $message)
    {
        //如果用web API给client发指令，这里可以不处理
        $db1 = Db::instance('db1');
        $message = str_replace(array("\r\n", "\r", "\n"), "", $message);
        $insert_id = $db1->insert('test')->cols(array('name' => "client_id=" . $client_id . " --- FG_onMessage=" . $message))->query();

        if (strncmp($message, ">MREG", 6) == 1) {
            //>MREG,PD-077,85008353819*24
            $xor = substr($message, strlen($message) - 2);
            $value = substr($message, 1, strlen($message) - 4);
            $s1 = Events::getXOR($value);
//            if ($xor == $s1) {
                Gateway::sendToClient($client_id, '@SREG,eggi.megowx.com,8902*24');
                return;
//            }
        } else if (strncmp($message, ">", 2) == 1) {
//            >85008353818,00,022140,A,N2444.9801,E12144.4167,0.00,0.00,310119,1014,6*77
//            >85008353819
            if (strlen($message) > 20) {
                $xor = substr($message, strlen($message) - 2);
                $value = substr($message, 1, strlen($message) - 4);
                $s1 = Events::getXOR($value);
//                if ($xor == $s1) {
                    Events::saverecord($client_id, $value);
//                }
                return;
            }
        }


//        $str = str_replace(array("\r\n", "\r", "\n"), "", $message);
//        if (!empty($str)) {
//            $clientid = $client_id;
//            $message_data = json_decode($str, true);
//            if ($message_data) {
//                // {"clientid":"7f0000010f3c00000001", "msg":"FF23"}
//                $clientid = $message_data['clientid'];
//                $str = $message_data['msg'];
//                Gateway::sendToClient($clientid, '=>' . $clientid . ' [' . $str . ']');
//            } else {
//                $insert_id = $db1->insert('test')->cols(array('name' => "client_id=" . $client_id . " --- FG_onMessage=" . $str))->query();
//                Gateway::sendToClient($clientid, $_SERVER['REMOTE_ADDR'] . '~' . $_SERVER['REMOTE_PORT'] . '~' . $clientid . ' [' . $str . ']');
//            }
//        }

    }

    public static function onClose($client_id)
    {

    }

    public static function getXOR($value)
    {
        if (empty($value)) {
            return "";
        }
        $aa = "";
        for ($i = 0; $i < strlen($value); $i++) {
            $bb = substr($value, $i, 1);
            if ($i == 0) {
                $aa = $bb;
            } else {
                $aa = $aa ^ $bb;
            }
        }

        $s1 = strtoupper(bin2hex($aa));
        return $s1;
    }

    public static function saverecord($client_id, $value)
    {
        if (empty($client_id) || empty($value)) {
            return;
        }

        $db1 = Db::instance('db1');

//        $db1->insert('test')->cols(array('name' => "client_id=" . $client_id . " --- saverecord=" . $value))->query();

        $record = explode(",", $value);
        if (!empty($record) && is_array($record)) {
            $mobile = $record[0];
            $mobile = str_replace(">", '', $mobile);
            $index = intval($record[1]);
            $state = $record[3];
            $lng = $record[5];
            $lat = $record[4];
            $vel = $record[6];
            $dir = $record[7];
            $zhixun = $record[9];
            $powerlevel = intval($record[10]);

            if ($state == 'V') {
                //strcomp($state,"V");
                return;
            }

//            $db1->insert('test')->cols(array('name' => $mobile))->query();

            $device_id = $db1->select('id')
                ->from('fa_feige_device')
                ->where('name= :name')
                ->bindValues(array('name'=>$mobile))
                ->single();

            if (empty($device_id)) {
//                $db1->insert('test')->cols(array('name' => '1'))->query();

                $device_id = $db1->insert('fa_feige_device') ->cols(
                    array(
                        'client_id' => $client_id,
                        'name' => $mobile,
                        'lng' => $lng,
                        'lat' => $lat
                    )
                 )->query();
            } else {
//                $db1->insert('test')->cols(array('name' => '2'))->query();

                $db1->update('fa_feige_device')->cols(
                    array(
                        'client_id' => $client_id,
                        'lng' => $lng,
                        'lat' => $lat,
                        'update_time' => date('Y-m-d H:i:s',time()),
                    )
                )->where("id=" . $device_id)->query();

//                $sql = "UPDATE `fa_feige_device` SET `client_id` = '".$client_id."',`lng` = '".$lng."',`lat` = '".$lat."' WHERE id=".$device_id;
//                $db1->query($sql);

            }

//            $db1->insert('test')->cols(array('name' => $device_id))->query();

            $db1->insert('fa_feige_records')->cols(
                array(
                    'device_id' => $device_id,
                    'mobile' => $mobile,
                    'index' => $index,
                    'state' => $state,
                    'lng' => $lng,
                    'lat' => $lat,
                    'vel' => $vel,
                    'dir' => $dir,
                    'zhixun' => $zhixun,
                    'powerlevel' => $powerlevel
                )
            )->query();


            Gateway::sendToClient($client_id, $mobile);
        }
    }

}
